package com.dragonfly.shutter.services;

import java.util.Date;

import com.dragonfly.shutter.DAOs.BrowseLogDAO;
import com.dragonfly.shutter.DAOs.FriendDAO;
import com.dragonfly.shutter.DAOs.PicCommentDAO;
import com.dragonfly.shutter.DAOs.PictureDAO;
import com.dragonfly.shutter.DAOs.ScoreDAO;
import com.dragonfly.shutter.DAOs.TagDAO;
import com.dragonfly.shutter.DAOs.UserDAO;
import com.dragonfly.shutter.beans.BrowseLog;
import com.dragonfly.shutter.beans.Friend;
import com.dragonfly.shutter.beans.PictureDetail;

/**
 * 图片中心服务类
 * @author 黄挺
 *
 */
public class PictureService {
	private PictureDAO pictureDAO;
	private BrowseLogDAO browseLogDAO;
	private PicCommentDAO picCommentDAO;
	private TagDAO tagDAO;
	private UserDAO userDAO;
	private ScoreDAO scoreDAO;
	private FriendDAO friendDAO;
	
	/**
	 * 图片中心服务类
	 * @param pictureID 图片ID
	 * @param userID 用户ID
	 * @param requestUrl 请求URL
	 * @return 图片详细Bean
	 * @throws Exception 图片访问权限受限
	 */
	public PictureDetail doService(String pictureID, Integer userID, String requestUrl) throws Exception {
		PictureDetail picture =  doDBOperate(pictureID, userID, requestUrl);
		
		//判断访问者是否拥有访问图片的权限
		if(picture.getFlagLimit() == "private" &&
				( userID == null || picture.getPicOwner().getUserID() != userID ) ) {
			throw new Exception("此图片属于私人所有，您无法访问");
		}
		else if(picture.getFlagLimit() == "friend") {
			Friend friend = friendDAO.selectOneFriend(picture.getPicOwner().getUserID(), userID);
			if(userID == null && friend == null)
				throw new Exception("此图片只有所有者的好友才能访问");
		}
		
		return picture;
	}
	
	/**
	 * 图片中心数据库操作函数
	 * @param pictureID 相册ID
	 * @param userID 用户ID
	 * @param requestUrl 请求URL
	 * @return 图片详细Bean
	 */
	public PictureDetail doDBOperate(String pictureID, Integer userID, String requestUrl) {
		PictureDetail picture = new PictureDetail();
		BrowseLog browseLog = new BrowseLog();
		
		if(userID != null )
			browseLog.setUserID(0);
		browseLog.setBrowseTime(new Date(System.currentTimeMillis()));
		browseLog.setUrl(requestUrl);
		
		picture = pictureDAO.selectPicByPicID(pictureID);
		picture.setComments(picCommentDAO.selectPagedCommentByPicID(pictureID, 0, 10));
		picture.setScoreNumber(scoreDAO.selectScoreNumber(pictureID));
		browseLogDAO.insertBrowseLog(browseLog);
		return picture;
	}
	
	public void setPictureDAO(PictureDAO pictureDAO) {
		this.pictureDAO = pictureDAO;
	}

	public void setBrowseLogDAO(BrowseLogDAO browseLogDAO) {
		this.browseLogDAO = browseLogDAO;
	}

	public void setPicCommentDAO(PicCommentDAO picCommentDAO) {
		this.picCommentDAO = picCommentDAO;
	}

	public void setTagDAO(TagDAO tagDAO) {
		this.tagDAO = tagDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public void setScoreDAO(ScoreDAO scoreDAO) {
		this.scoreDAO = scoreDAO;
	}

	public void setFriendDAO(FriendDAO friendDAO) {
		this.friendDAO = friendDAO;
	}
}
